package kr.hyosang.dkbs.kiosk.server.news;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.hyosang.dkbs.kiosk.server.data.News;
import kr.hyosang.dkbs.kiosk.server.data.entity.NewsEntity;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;


public class Register extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3658059919664487694L;
	
	private static final Logger log = Logger.getLogger(Register.class.getName());

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String title, content, startDt, endDt;
		title = content = startDt = endDt = "";
		
		try {
			ServletFileUpload upload = new ServletFileUpload();
			
			FileItemIterator iter = upload.getItemIterator(req);
			while(iter.hasNext()) {
				FileItemStream item = iter.next();
				if(item.isFormField()) {
					String field = item.getFieldName();
					String cont = Streams.asString(item.openStream(), "UTF-8");
					if("inputTitle".equals(field)) {
						title = cont;
					}else if("inputContent".equals(field)) {
						content = cont;
					}else if("inputStartDt".equals(field)) {
						startDt = cont;
					}else if("inputEndDt".equals(field)) {
						endDt = cont;
					}
				}else {
					log.log(Level.INFO, "file field : " + item.getName());
				}
			}
		}catch(FileUploadException e) {
			log.log(Level.INFO, "error", e);
		}
		
		
		News news = new News();
		NewsEntity item = new NewsEntity();
		item.title = title;
		item.content = content;
		item.startDate = startDt;
		item.endDate = endDt;
		
		news.addEntity(item);
		
		resp.sendRedirect("/news/list.jsp");
	}

}
